package game.utils;

import hx.utils.SoundManager;
import hx.display.Button;
import hx.utils.SceneManager;
import hx.events.Keyboard;
import game.worlds.Key;
import game.worlds.GameRole;
import hx.events.KeyboardEvent;
import hx.core.Hxmaker;

using Reflect;

/**
 * 键盘工具
 */
class KeybarodTools {
	/**
	 * 所有按键是否按下状态记录
	 */
	public static var keyMap:Map<Int, Bool> = new Map<Int, Bool>();

	/**
	 * 是否可用
	 */
	public static var enable:Bool = true;

	/**
	 * 初始化键盘功能
	 */
	public static function init():Void {
		var stage = Hxmaker.engine.stages[0];
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
	}

	@:noCompletion private static function onKeyDown(e:KeyboardEvent):Void {
		keyMap.set(e.keyCode, true);
		if (enable)
			for (key in __keys) {
				key.onKeyDown(e.keyCode);
			}
		var view = SceneManager.getInstance().currentScene;
		if (view != null) {
			switch (e.keyCode) {
				case Keyboard.J:
					// 确定，可以快速触发ok组件
					var button:Button = view.getProperty("ok");
					if (button != null) {
						SoundManager.getInstance().playEffect(Button.clickSoundEffectId);
						button.clickEvent();
					}
				case Keyboard.K:
					// 取消，可以快速触发back组件
					var button:Button = view.getProperty("back") ?? view.getProperty("close");
					if (button != null) {
						SoundManager.getInstance().playEffect(Button.clickSoundEffectId);
						button.clickEvent();
					}
			}
		}
	}

	@:noCompletion private static function onKeyUp(e:KeyboardEvent):Void {
		keyMap.set(e.keyCode, false);
		if (enable)
			for (key in __keys) {
				key.onKeyUp(e.keyCode);
			}
	}

	/**
	 * 是否按下了某个按键
	 * @param key 按键键码
	 * @return Bool
	 */
	public static function isKeyDown(role:GameRole, key:Int):Bool {
		return keyMap.exists(key) && keyMap.get(key);
	}

	private static var __keys:Array<Key> = [];

	/**
	 * 添加按键侦听
	 * @param key 
	 */
	public static function addKeyListener(key:Key):Void {
		if (__keys.indexOf(key) == -1) {
			__keys.push(key);
		}
	}

	/**
	 * 删除按键侦听
	 * @param key 
	 */
	public static function removeKeyListener(key:Key):Void {
		__keys.remove(key);
	}

	/**
	 * 测试组合键
	 * @param key 
	 * @param testGroupKey 
	 * @return Bool
	 */
	public static function testGroupKey(keys:Array<Int>, groupKeys:Array<Int>):Bool {
		if (groupKeys.length > keys.length) {
			return false;
		} else if (groupKeys.length < keys.length) {
			keys = keys.slice(keys.length - groupKeys.length);
		}
		// 如果技能属于AD键的，则需要判断keys是否需要进行转换处理
		if (groupKeys[0] == Keyboard.A || groupKeys[0] == Keyboard.D) {
			if (keys[0] == Keyboard.A || keys[0] == Keyboard.D) {
				if (groupKeys[0] != keys[0]) {
					keys = keys.map(v -> {
						if (v == Keyboard.A || v == Keyboard.D) {
							return v == Keyboard.A ? Keyboard.D : Keyboard.A;
						}
						return v;
					});
				}
			}
		}
		for (index => value in keys) {
			if (value != groupKeys[index]) {
				return false;
			}
		}
		return true;
	}
}
